<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 警告框 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>

      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 级联选择框 -->
          <el-cascader
            v-model="selectedKeys"
            :options="catelist"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tabs标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数的 按钮 -->
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="addFromDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数列表 -->
          <el-table :data="manyData" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <!-- 通过作用域插槽进行数据循环 
              通过scope接收数据-->
              <template slot-scope="scope">
                <!-- 循环渲染标签 -->
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleCloseAttr(i, scope.row)"
                  >{{ item }}
                </el-tag>

                <!-- 输入框与按钮的切换 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <!-- 作用域插槽 -->
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeCate(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性的按钮 -->
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="addFromDialogVisible = true"
            >添加属性</el-button
          >

          <!-- 静态属性列表 -->
          <el-table :data="onlyData" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <!-- 通过作用域插槽进行数据循环 
              通过scope接收数据-->
              <template slot-scope="scope">
                <!-- 循环渲染标签 -->
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleCloseAttr(i, scope.row)"
                  >{{ item }}
                </el-tag>

                <!-- 输入框与按钮的切换 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <!-- 作用域插槽 -->
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeCate(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 添加属性、参数对话框 -->
      <el-dialog
        :title="'添加' + TitleText"
        :visible.sync="addFromDialogVisible"
        width="50%"
        @close="addFormDialogClosed"
      >
        <!-- 表单验证 -->
        <el-form
          :model="addCateForm"
          :rules="addCateFormRules"
          ref="addCateFormRef"
          label-width="100px"
        >
          <el-form-item :label="TitleText" prop="attr_name">
            <el-input v-model="addCateForm.attr_name"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addFromDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑框 -->
      <el-dialog
        :title="'' + TitleText"
        :visible.sync="editFromDialogVisible"
        width="50%"
        @close="editFormDialogClosed"
      >
        <!-- 表单验证 -->
        <el-form
          :model="editCateForm"
          :rules="editCateFormRules"
          ref="editCateFormRef"
          label-width="100px"
        >
          <el-form-item :label="TitleText" prop="attr_name">
            <el-input v-model="editCateForm.attr_name"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editFromDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品数据列表
      catelist: [],
      // 级联选择框pros的配置
      cateProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      // 级联选择框选中的id
      selectedKeys: [],

      // 标签页
      activeName: "many",
      // 动态参数逇数据
      manyData: [],
      // 静态属性的数据
      onlyData: [],

      // 控制添加属性、参数对话框的显示与隐藏
      addFromDialogVisible: false,

      // 表单数据
      addCateForm: {
        attr_name: "",
      },

      // 表单验证规则
      addCateFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },

      // 控制编辑框的显示与隐藏
      editFromDialogVisible: false,

      // 编辑框的表单数据
      editCateForm: {
        attr_name: "",
      },

      // 表单验证规则
      editCateFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    // 获取商品分类数据列表
    this.getCateList();
  },
  computed: {
    //  如果按钮需要被禁用，则返回true，否则返回false
    isBtnDisabled() {
      if (this.selectedKeys.length !== 3) {
        return true;
      }
      return false;
    },
    // 但选中对的三级分类的id
    CateId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2];
      }
      return null;
    },

    // 得到标题文本
    TitleText() {
      if (this.activeName === "many") {
        return "动态参数";
      }
      return "静态属性";
    },
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$axios.get("categories");
      if (res.meta.status != 200) {
        return this.$message.error("获取商品分类数据失败");
      }
      this.catelist = res.data;
      // console.log(this.catelist);
    },

    // handleChange级联选择框发生变化时
    handleChange() {
      this.getParamsData();
    },

    // tab 页签点击事件的处理函数
    handleClick() {
      // console.log(this.activeName);
      this.getParamsData();
    },

    async getParamsData() {
      // 控制级联选择器的选择范围

      // console.log(this.selectedKeys);
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = [];
        // 相对应的数据源也要清空
        this.manyData = [];
        this.onlyData = [];
        return;
      }

      // 证明选中的是三级
      // 根据所选分类的ID，和当前所处的面板，获取对应的参数
      const { data: res } = await this.$axios.get(
        `categories/${this.CateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("加载失败");
      }
      console.log(res.data);
      // 将得到的数组进行按空格分割
      res.data.forEach((item) => {
        // 使用三元表达式
        // 如果数组为空，则不进行切割，直接返回一个空的数组。
        // 以空格进行分割
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];

        // 所以每一行数据都有自己的inputVisible和inputValue，这样就不会出现共用的问题了。
        // 控制文本框的显示与隐藏
        item.inputVisible = false;
        // 绑定文本输入框的值
        item.inputValue = "";
      });
      if (this.activeName === "many") {
        this.manyData = res.data;
      } else {
        this.onlyData = res.data;
      }
    },

    // 监听对话框关闭之后的
    addFormDialogClosed() {
      this.addCateForm = {};
    },

    // 点击确定按钮，添加属性和参数
    addParams() {
      // 提交表单
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error("表单校验失败");
        }
        // 发送post请求
        const { data: res } = await this.$axios.post(
          `categories/${this.CateId}/attributes`,
          {
            attr_name: this.addCateForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status != 201) {
          return this.$message.error("添加失败");
        }
        this.getParamsData();
        this.$message.success("成功添加");
        this.addFromDialogVisible = false;
      });
    },

    // 编辑框显示
    async showEditDialog(cate) {
      // console.log(cate);
      this.editFromDialogVisible = true;
      const { data: res } = await this.$axios.get(
        `categories/${cate.cat_id}/attributes/${cate.attr_id}`,
        {
          params: {
            attr_sel: this.activeName,
          },
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("表单显示失败");
      }
      this.editCateForm = res.data;
    },

    // 点击确定按钮，进行修改操作
    editParams() {
      // 在提交表单之前，先进行表单验证
      this.$refs.editCateFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.eeror("表单验证失败");
        }

        // 表单验证成功，提交表单数据
        const { data: res } = await this.$axios.put(
          `categories/${this.editCateForm.cat_id}/attributes/${this.editCateForm.attr_id}`,
          {
            attr_name: this.editCateForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("表单数据更新失败");
        }
        this.$message.success("表单更新成功");
        this.getParamsData();
        this.editFromDialogVisible = false;
      });
    },
    // 编辑表单重置
    editFormDialogClosed() {
      this.editCateForm = {};
    },

    // 业务逻辑删除
    async removeCate(attr_id) {
      // 在删除之前先弹框确认是否删除
      const confirmResult = await this.$confirm(
        "此操作将永久删除该数据, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除操作");
      }
      // 进行删除操作
      const { data: res } = await this.$axios.delete(
        `categories/${this.CateId}/attributes/${attr_id}`
      );
      if (res.meta.status !== 200) {
        return this.$message.error("删除参数列表失败");
      }
      this.$message.success("删除成功");
      this.getParamsData();
      this.editFromDialogVisible = false;
    },

    // 按下enter键或者失去焦点触发函数
    handleInputConfirm(row) {
      //  trim() 方法用于删除字符串的头尾空格
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }

      // console.log("ok");
      // 如果没有return ,则证明输入的内容，需要做后续处理
      // 获取输入框里面的值
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;

      this.saveAttrVals(row);
    },

    // 保存attr_vals的值
    async saveAttrVals(row) {
      // 发起put请求
      const { data: res } = await this.$axios.put(
        `categories/${this.CateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(" "),
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("添加参数失败");
      }
      this.$message.success("添加参数成功");
    },
    // 点击触发输入框显示事件
    showInput(row) {
      row.inputVisible = true;
      // 让文本框自动获得焦点
      // $nextTick 方法的作用，就是当页面上元素被重新渲染之后，才会指定回调函数中的代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    // 删除参数下的可选项
    handleCloseAttr(index, row) {
      // 删除数组对应索引位的字符
      row.attr_vals.splice(index, 1);
      // 刷新数据
      this.saveAttrVals(row);
    },
  },
};
</script>

<style scoped>
.cat_opt {
  margin: 15px 0;
}
.el-cascader {
  width: 300px;
}
.el-tag {
  margin: 7px 15px;
}
.input-new-tag {
  width: 120px;
}
</style>